from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import *
import re
from CONFIG import *


"""
Returns the path to a template in the static templates
directory, given it's name.
"""
def getTemplatePath(name):
    return "templates/" + name + ".html"

"""
Checks if the current user is valid and an admin,
if not it redirects the user to a login page.
Copied from the google.appengine.ext.webapp.utils.@login_required
"""
def admin_required(handler_method):
    def check_admin(self, *args):
        if not users.is_current_user_admin():
            self.redirect(GAPYCDN_CONFIG["base_url"])
            return
        else:
            handler_method(self, *args)
    return check_admin

"""
Writes the default header and footer template.
"""
def writeHeader(handler, title):
    t = {}
    t["base_url"] = GAPYCDN_CONFIG["base_url"]
    t["title"] = title
    t["logout_url"] = users.create_logout_url(GAPYCDN_CONFIG["base_url"])
    t["user_nick"] = users.get_current_user().nickname()
    handler.response.out.write(template.render(getTemplatePath("header"), t))


"""
Writes the default footer.
"""
def writeFooter(handler):
    handler.response.out.write(template.render(getTemplatePath("footer"), {}))

"""
A django custom filter that converts byte values to things like 1k, 1mb etc.
"""
def fileSize(size, arg):
    if size < 1024:
        return str(size) + "<span class=\"filesize\">B</span>"
    elif size < 1048576:
        return str(size/1024) + "<span class=\"filesize\">KB</span>"
    else:
        return str(size/1048576) + "<span class=\"filesize\">MB</span>"

"""
HTMLises a path by substituting / for the right entity.
"""
def htmlise_path(path):
    return re.sub("/", "&#47;", path)

"""
Used to register custom filters.
"""
register = webapp.template.create_template_register()

# Register filters here!
register.filter(fileSize)

# Registers this module as a template filter library
try:
    webapp.template.register_template_library("gaecdn.utils")
except:
    webapp.template.register_template_library("gapycdn.gaecdn.utils")

